from django.shortcuts import get_object_or_404
from django.conf.urls.defaults import url
from dwa.util import method_dispatcher, make_url
from dwa.urlresolvers import BaseRegexURLResolver

id_re = r'(?P<id>\d+)'

class Resource(BaseRegexURLResolver):
    def list(self, request):
        return self.queryset

    def detail(self, request, obj):
        # By default, pass it through to the serializer.
        return obj

    def list_entry(self, obj):
        return dict(id=obj.pk, url=make_url([self.url, str(obj.pk)]))
    
    list_view = method_dispatcher('list_view')
    def list_view_GET(self, request):
        return {'contents': [self.list_entry(obj) for obj in self.list(request)]}

    detail_view = method_dispatcher('detail_view')
    def detail_view_GET(self, request, id):
        obj = get_object_or_404(self.queryset, pk=id)
        return self.detail(request, obj)

    def detail_view_PUT(self, request, id):
        obj = get_object_or_404(self.queryset, pk=id)
        new_content = request.POST['content']
        obj.contents = new_content
        obj.save()
        return self.detail(request, obj)

    @property
    def url_patterns(self):
        pat = [url('^$', self.list_view)]
        if self.detail_view is not None:
            pat.append(url('^%s/$' % id_re, self.detail_view))
        return pat

    def __init__(self):
        super(Resource, self).__init__(self.regex, None)

class ResourceCollection(list):
    def url_patterns(self):
        patterns = []
        for cls in self:
            patterns.extend(cls())
        return patterns
